package system.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import system.dao.ResourceDao;
import system.dao.UserDao;
import system.model.Syresources;
import system.model.Syrole;
import system.model.SyroleSyresources;
import system.model.Syuser;
import system.model.SyuserSyrole;
import system.service.AuthServiceI;

import common.service.impl.BaseServiceImpl;




/**
 * 权限Service
 * 
 * 
 */
@Service("authService")
public class AuthServiceImpl extends BaseServiceImpl implements AuthServiceI {

	private ResourceDao<Syresources> resourcesDao;
	private UserDao<Syuser> userDao;

	public UserDao<Syuser> getUserDao() {
		return userDao;
	}

	@Autowired
	public void setUserDao(UserDao<Syuser> userDao) {
		this.userDao = userDao;
	}

	public ResourceDao<Syresources> getResourcesDao() {
		return resourcesDao;
	}

	@Autowired
	public void setResourcesDao(ResourceDao<Syresources> resourcesDao) {
		this.resourcesDao = resourcesDao;
	}

	@Cacheable(value = "syproAuthCache", key = "'offResourcesList'")
	@Transactional(readOnly = true)
	public List<Syresources> offResourcesList() {
		return resourcesDao.find("from Syresources t where t.onoff != '1'");
	}

	@Cacheable(value = "syproAuthCache", key = "'getSyresourcesByRequestPath'+#requestPath")
	@Transactional(readOnly = true)
	public Syresources getSyresourcesByRequestPath(String requestPath) {
		return resourcesDao.get("from Syresources t where t.src=?", requestPath);
	}

	//@Cacheable(value = "syproAuthCache", key = "'checkAuth'+#userId+#requestPath")
	@Transactional(readOnly = true)
	public boolean checkAuth(String userId, String requestPath) {
		//System.out.println("sdfsa");
		boolean b = false;
		Syuser syuser = userDao.get(Syuser.class, userId);
		Set<SyuserSyrole> syuserSyroles = syuser.getSyuserSyroles();// 用户和角色关系
		for (SyuserSyrole syuserSyrole : syuserSyroles) {
			Syrole syrole = syuserSyrole.getSyrole();
			Set<SyroleSyresources> syroleSyreources = syrole.getSyroleSyresourceses();// 角色和资源关系
			
			for (SyroleSyresources syroleSyreource : syroleSyreources) {
				Syresources syresources = syroleSyreource.getSyresources();
			//	System.out.println(syresources.getSrc()+"----------------"+requestPath);
				if (syresources.getSrc() != null && requestPath.equals(syresources.getSrc())) {
					return true;
				}
			}
		}
		return b;
	}

}
